package com.hghivln.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hghivln.constants.Constants;
import com.hghivln.mapper.*;
import com.hghivln.pojo.domain.*;
import com.hghivln.pojo.dto.CareHistoryDto;
import com.hghivln.pojo.dto.CareOrderDto;
import com.hghivln.pojo.dto.CareOrderFormDto;
import com.hghivln.pojo.dto.CareOrderItemDto;
import com.hghivln.pojo.vo.AjaxResult;
import com.hghivln.pojo.vo.CareHistoryVo;
import com.hghivln.service.CareService;
import com.hghivln.utils.IdGeneratorSnowflake;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(methods = {
        @Method(name = "saveCareOrderItem", retries = 0, timeout = 6000),
        @Method(name = "saveOrUpdateCareHistory", retries = 0)
})
public class CareServiceImpl implements CareService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private CareHistoryMapper careHistoryMapper;

    @Autowired
    private CareOrderMapper careOrderMapper;

    @Autowired
    private CareOrderItemMapper careOrderItemMapper;

    @Autowired
    private RegistrationMapper registrationMapper;

    @Autowired
    private MedicinesMapper medicinesMapper;

    @Autowired
    private OrderChargeItemMapper orderChargeItemMapper;


    @Override
    public AjaxResult saveOrUpdateCareHistory(CareHistoryDto careHistoryDto, User user) {
        CareHistory careHistory = new CareHistory();
        BeanUtils.copyProperties(careHistoryDto, careHistory);
        careHistory.setUserId(user.getUserId());
        careHistory.setUserName(user.getUserName());
        careHistory.setDeptId(user.getDeptId());
        careHistory.setCareTime(DateUtil.date());
        Dept dept = deptMapper.selectByDeptId(user.getDeptId());
        careHistory.setDeptName(dept.getDeptName());
        // 做修改
        if (ObjectUtils.isNotEmpty(careHistory.getChId())) {
            int i = careHistoryMapper.updateById(careHistory);
            if (i == 1) {
                return AjaxResult.success("操作成功", careHistory.getChId());
            } else {
                return AjaxResult.fail("该病例不存在");
            }
        } else {
            // 做添加
            careHistory.setChId(IdGeneratorSnowflake.generatorIdWithProfix(Constants.ID_PROFIX_CH));
            careHistoryMapper.insert(careHistory);
            return AjaxResult.success("操作成功", careHistory.getChId());
        }
    }

    @Override
    public CareHistoryVo selectCareHistoryByRegId(String regId) {
        CareHistory careHistory = careHistoryMapper.selectCareHistoryByRegId(regId);
        if (ObjectUtils.isEmpty(careHistory)) {
            // 第一次加载，没有病例数据
            return null;
        }
        CareHistoryVo careHistoryVo = new CareHistoryVo();
        BeanUtils.copyProperties(careHistory, careHistoryVo);
        return careHistoryVo;
    }

    @Override
    public AjaxResult queryCareOrdersByChId(String chId) {
        // 根据病例ID查询药用处方信息
        List<CareOrder> careOrderList = careOrderMapper.selectCareOrderListByChId(chId);
        List<Map<String, Object>> list = new ArrayList<>();
        for (CareOrder careOrder : careOrderList) {
            // 根据处方Id查询处方详情
            List<CareOrderItem> careOrderItemList = careOrderItemMapper.selectCareOrderItemListByCoId(careOrder.getCoId(), null);
            Map<String, Object> map = new HashMap<>();
            map.put("careOrder", careOrder);
            map.put("careOrderItems", careOrderItemList);
            list.add(map);
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult saveCareOrderItem(CareOrderFormDto careOrderFormDto) {
        CareOrderDto careOrderDto = careOrderFormDto.getCareOrder();
        //根据病例ID查询病历信息
        CareHistory careHistory = this.queryCareHistoryByChId(careOrderDto.getChId());
        if (ObjectUtils.isEmpty(careHistory)) {
            AjaxResult.fail("病例单号不存在，请核实后再提交");
        }
        CareOrder careOrder = new CareOrder();
        BeanUtils.copyProperties(careOrderDto, careOrder);
        // 保存处方单
        User user = (User) careOrderFormDto.getUser();
        careOrder.setUserId(user.getUserId());
        careOrder.setPatientName(careHistory.getPatientName());
        careOrder.setPatientId(careHistory.getPatientId());
        careOrder.setCreateBy(user.getUserName());
        careOrder.setCreateTime(DateUtil.date());
        careOrder.setCoId(IdGeneratorSnowflake.generatorIdWithProfix(Constants.ID_PROFIX_CO));
        int i = careOrderMapper.insert(careOrder);
        // 保存处方详情
        List<CareOrderItemDto> careOrderItems = careOrderFormDto.getCareOrderItems();
        for (CareOrderItemDto careOrderItemDto : careOrderItems) {
            CareOrderItem careOrderItem = new CareOrderItem();
            BeanUtils.copyProperties(careOrderItemDto, careOrderItem);
            careOrderItem.setItemId(IdGeneratorSnowflake.generatorIdWithProfix(Constants.ID_PROFIX_ITEM));
            careOrderItem.setCreateTime(DateUtil.date());
            careOrderItem.setCoId(careOrder.getCoId());
            careOrderItem.setStatus(Constants.ORDER_STATUS_0);
            careOrderItemMapper.insert(careOrderItem);
        }
        return AjaxResult.success(i);
    }

    /**
     * 判断该处方详情是否存在
     * 存在并且是未支付状态，删除详情
     * 更新处方表的处方全额all_amount
     */
    @Override
    public AjaxResult deleteCareOrderItemById(String itemId) {
        CareOrderItem careOrderItem = careOrderItemMapper.selectById(itemId);
        if (ObjectUtils.isEmpty(careOrderItem)) {
            return AjaxResult.fail("处方详情ID不存在");
        }
        if (!careOrderItem.getStatus().equals(Constants.ORDER_STATUS_0)) {
            return AjaxResult.fail("【" + itemId + "】不是未支付状态，不能删除");
        }
        // 拿到主表ID
        String coId = careOrderItem.getCoId();
        int i = careOrderItemMapper.deleteById(itemId);
        // 根据主表ID 去查询 处方详情
        QueryWrapper<CareOrderItem> qw = new QueryWrapper<>();
        qw.eq(CareOrderItem.COL_CO_ID, coId);
        List<CareOrderItem> careOrderItemList = careOrderItemMapper.selectList(qw);
        // 如果有数据重新计算价格，没数据则直接删除主表
        if (CollectionUtil.isNotEmpty(careOrderItemList)) {
            BigDecimal allAmount = new BigDecimal("0");
            for (CareOrderItem orderItem : careOrderItemList) {
                BigDecimal amount = orderItem.getAmount();
                allAmount = allAmount.add(amount);
            }
            CareOrder careOrder = careOrderMapper.selectById(coId);
            careOrder.setAllAmount(allAmount);
            careOrderMapper.updateById(careOrder);
        } else {
            careOrderMapper.deleteById(coId);
        }
        return AjaxResult.success(i);
    }

    @Override
    public AjaxResult visitComplete(String regId) {
        Registration registration = registrationMapper.selectById(regId);
        if (ObjectUtils.isEmpty(registration)) {
            return AjaxResult.fail("【" + regId + "】挂号单号不存在，请核对后再提交");
        }
        if (!registration.getRegStatus().equals(Constants.REG_STATUS_2)) {
            return AjaxResult.fail("【" + regId + "】状态不是就诊中状态，不能完成就诊");
        }
        registration.setRegStatus(Constants.REG_STATUS_3);
        return AjaxResult.toAjax(registrationMapper.updateById(registration));
    }

    @Override
    public List<CareOrder> selectCareOrdersByChId(String chId) {
        return careOrderMapper.selectCareOrderListByChId(chId);
    }

    @Override
    public List<CareOrderItem> selectCareOrderItemByCoId(String coId, String status) {
        return careOrderItemMapper.selectCareOrderItemListByCoId(coId, status);
    }

    @Override
    public String doMedicine(List<String> itemIds) {
        //执行发药  情况1  库存够正常走   情况2 库存不够  返回哪个药品库存不够，只发够的药品  其它的让患者自己去退费
        List<CareOrderItem> careOrderItems = careOrderItemMapper.selecByItemIds(itemIds);
        StringBuffer msg = new StringBuffer();
        for (CareOrderItem careOrderItem : careOrderItems) {
            int i = medicinesMapper.deductionMedicinesStorage(Long.valueOf(careOrderItem.getItemRefId()), careOrderItem.getNum().longValue());
            if (i > 0) { // 库存够
                // 更新处方详情状态
                careOrderItem.setStatus(Constants.ORDER_DETAILS_STATUS_3);
                careOrderItemMapper.updateById(careOrderItem);
                // 更新收费详情状态
                OrderChargeItem orderChargeItem = new OrderChargeItem();
                orderChargeItem.setItemId(careOrderItem.getItemId());
                orderChargeItem.setStatus(Constants.ORDER_DETAILS_STATUS_3);
                orderChargeItemMapper.updateById(orderChargeItem);

            } else { // 库存不够
                msg.append("【" + careOrderItem.getItemName() + "】发药失败\n");
            }
        }
        if (StringUtils.isBlank(msg)) {
            msg.append("发药成功");
            return msg.toString();
        } else {
            msg.append("原因：库存不足");
            return msg.toString();
        }
    }


    public CareHistory queryCareHistoryByChId(String chId) {
        return this.careHistoryMapper.selectById(chId);
    }
}
